/**
 * Copyright (C) 2013 AirChina
 *
 * @description:
 * @version:v1.0.0
 */
package com.china.api.wechat.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;





import com.china.api.wechat.SpringContext;
import com.china.api.wechat.processor.main.Delegate;
/**
 * @Description:
 * @author:larry
 * @Created:2013-11-20上午10:21:05
 */
@SuppressWarnings("serial")
public class WeChatServlet extends HttpServlet {
	
	private final Logger log = LoggerFactory.getLogger(getClass());
	private static final int SERVER_PORT = 80;
	private Delegate delegate = new Delegate();
	
	public WeChatServlet() {
		super();
	}
	
	@Override
	public void init() throws ServletException {
		SpringContext.init();
		log.info("init finished...");
		super.init();
	}
	

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Map<String, String[]> params = request.getParameterMap();
		for (Entry<String, String[]> p : params.entrySet()) {
			String key = p.getKey();
			if (key.equals("echostr")) {
				String[] vals = p.getValue();
				for (String val : vals) {
					out.write(val);
				}
			}
		}
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream is = request.getInputStream();
		int temp;
		while ((temp = is.read()) != -1) {
			baos.write(temp);
		}
		String strContent = baos.toString("utf-8");
		log.debug("post:" + strContent);
		String ret = null;
		try {
			ret = delegate.process(strContent);
			if(ret!=null)
				out.write(ret);
			log.debug("response"+ret);
		} catch (Exception e) {
			log.error("process error.", e);
		}finally{
			out.flush();
			out.close();
		}
	}

}
